package com.kittlen.managementSystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.kittlen.managementSystem.entity.Admin;
import com.kittlen.managementSystem.entity.MySqlLimit;
import com.kittlen.managementSystem.entity.Notice;
import com.kittlen.managementSystem.entity.Result;
import com.kittlen.managementSystem.service.INoticeService;
import com.kittlen.managementSystem.utils.FileUpload;
import com.kittlen.managementSystem.utils.IdWorker;
import com.kittlen.managementSystem.utils.ObjectUtil;
import com.kittlen.managementSystem.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 公告表 前端控制器
 * </p>
 *
 * @author kittlen
 * @since 2021-01-26
 */
@ImportResource("classpath:/springmvc-servlet.xml")
@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Value("${Upload_NoticeFile}")
    private String noticeFile;

    @Value("${Upload_CarouselFile}")
    private String carouselFile;

    @Resource
    INoticeService iNoticeService;

    IdWorker idWorker=new IdWorker(1,1,1);

    /**
     * 公告查询
     *
     * @param notice
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("selects")
    public Result selects(Notice notice, @RequestParam(required = false, defaultValue = "0") int page,
                          @RequestParam(required = false, defaultValue = "0") int limit,
                          @RequestParam(required = false, defaultValue = "0") int isShow,
                          @RequestParam(required = false, defaultValue = "") String startTime,
                          @RequestParam(required = false, defaultValue = "") String endTime) {
        Result result = new Result();
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNoEmpty(notice.getNoticeId())) {
            queryWrapper.like("notice_id", notice.getNoticeId());
        }
        if (ObjectUtil.isNoEmpty(notice.getTitle())) {
            queryWrapper.like("title", notice.getTitle());
        }
        if (ObjectUtil.isNoEmpty(notice.getNoticeType())) {
            queryWrapper.like("notice_type", notice.getNoticeType());
        }
        if (ObjectUtil.isNoEmpty(notice.isShow())&&isShow==1) {//显示轮播
            queryWrapper.eq("is_show", "1");
        }
        if (ObjectUtil.isNoEmpty(notice.getAdmin())) {
            if (ObjectUtil.isNoEmpty(notice.getAdmin().getAdminId())) {
                queryWrapper.like("n.admin_id", notice.getAdmin().getAdminId());
            }
        }
        if (ObjectUtil.isNoEmpty(startTime)) {
            queryWrapper.ge("create_date", startTime);
        }
        if (ObjectUtil.isNoEmpty(endTime)) {
            endTime = TimeUtil.getSpecifiedDayAfter(endTime);
            queryWrapper.le("create_date", endTime);
        }
        if (page!=-1) {
            MySqlLimit mySqlLimit=new MySqlLimit(page,limit);
            queryWrapper.last("LIMIT "+mySqlLimit.getOffset()+","+mySqlLimit.getRows());
        }
        queryWrapper.orderByDesc("create_date");
        List<Notice> list = iNoticeService.selects(queryWrapper);
        result.setData(list);
        queryWrapper.last("");
        result.setCount(iNoticeService.count(queryWrapper));
        return result;
    }

    @CrossOrigin
    @RequestMapping("/imageUpload")
    public Result imageUpload(MultipartFile file, HttpServletRequest request)  {
        Result result= FileUpload.fileSave(file,request,ObjectUtil.isNoEmpty(noticeFile)?noticeFile:"/StaticRes/NoticePath/");
        return result;

    }

    /**
     * 公告添加
     *
     * @param notice
     * @return
     */
    @RequestMapping("/insert")
    public Result insert(Notice notice,HttpServletRequest request) {
        Result result = new Result();
        try {
            Admin admin= (Admin) SessionController.getSession(request,"user");
            notice.setAdmin(admin);
        }catch (ClassCastException e){
            result.setCode(result.RESULT_ERROR);
            result.setMsg("用户信息错误,请重新登陆");
            return result;
        }
        notice.setNoticeId(idWorker.nextId()+"");
        if (iNoticeService.insert(notice)>0) {
            result.setData(notice);
            result.setMsg("公告添加成功");
        } else {
            result.setCode(result.RESULT_ERROR);
            result.setMsg("公告添加失败");
        }
        return result;
    }

    /**
     * 公告修改
     *
     * @param notice
     * @return
     */
    @RequestMapping("/update")
    public Result update(Notice notice) {
        Result result = new Result();
        if (iNoticeService.updateById(notice)) {
            result.setData(notice);
            result.setMsg("公告信息修改成功");
        } else {
            result.setCode(result.RESULT_ERROR);
            result.setMsg("公告信息修改失败");
        }
        return result;
    }

    /**
     * 轮播展示修改
     *
     * @param carouselsStr
     * @return
     */
    @RequestMapping("/updateByCarousel")
    public Result updateByCarousel(String carouselsStr) {
        Result result = new Result();
        Notice.CarouselsUpdate carouselsUpdate=new Gson().fromJson(carouselsStr, Notice.CarouselsUpdate.class);
        try {
            if(ObjectUtil.isNoEmpty(carouselsUpdate.getOldNoticeId())) {
                iNoticeService.update(new UpdateWrapper<Notice>().in("notice_id", carouselsUpdate.getOldNoticeId()).set("is_show", 0));
            }
            if(ObjectUtil.isNoEmpty(carouselsUpdate.getNewNoticeId())) {
                iNoticeService.update(new UpdateWrapper<Notice>().in("notice_id", carouselsUpdate.getNewNoticeId()).set("is_show", 1));
            }
            result.setMsg("公告信息修改成功");
        }catch (Exception e){
            result.setCode(result.RESULT_ERROR);
            result.setMsg("公告信息修改失败");
        }
        return result;
    }

    /**
     * 文件上传,layui的文件上传为多文件列表上传的话,也同样使用MultipartFile file即可,它原理是多次调用同一个接口
     * @param file
     * @param
     * @param request
     * @return
     */
    @RequestMapping("/fileUpload")
    public Result fileUpload(MultipartFile file, String noticeId, HttpServletRequest request){
        Result result=new Result();
        if(!ObjectUtil.isNoEmpty(noticeId)){
            result.setMsg("公告信息异常,重试");
            result.setCode(result.RESULT_ERROR);
            return result;
        }
        if (file.isEmpty()) {
            result.setMsg("文件上传异常");
            result.setCode(result.RESULT_ERROR);
        } else{
            Map<String,String> map = FileUpload.upload(file, ObjectUtil.isNoEmpty(carouselFile)?carouselFile:"/StaticRes/CarouselPath/", request);
            if(ObjectUtil.isEmpty(map.get("fileRelativePath"))){
                result.setCode(Result.RESULT_ERROR);
                result.setMsg("上传失败");
                return result;
            }
            if(iNoticeService.update(new UpdateWrapper<Notice>().eq("notice_id",noticeId).set("notice_img",map.get("fileRelativePath")))){
                result.setMsg("上传成功");
            }else{
                result.setCode(result.RESULT_ERROR);
                result.setMsg("上传失败");
            }
        }

        return result;
    }

    /**
     * 公告删除
     *
     * @param notice
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Notice notice) {
        Result result = new Result();
        if (iNoticeService.removeById(notice)) {
            result.setMsg("删除成功");
        } else {
            result.setMsg("删除失败");
            result.setCode(result.RESULT_ERROR);
        }
        return result;
    }

}

